var weixinUrl = 'https://wx.qq.com';
var groupChatList;
var contactList;
var dialogFromUserName;
var dialogToUserName;
var pageNo=1;
var pageSize=10;
var isLastPage=false;

$(function () {
    /**
     * 二维码弹窗
     */
    $('a[target="_jeesnsOpen"]').on('click',function() {
        var url = $(this).attr('href');
        var title = $(this).attr('title');
        var width = $(this).attr('width');
        var height = $(this).attr('height');
        if(width == undefined || width == ""){
            width = "500px";
        }
        if(height == undefined || height == ""){
            height = "300px";
        }
        jeesnsDialog.open(url,title,width,height,null,function () {
            closeRegister();
        });
        return false;
    });
    /**
     * 点击打开微服务二维码的窗口
     */
    $("#addWechat").bind("click",function () {
        myManager.begin();
    });
    /**
     * 关闭登录二维码弹窗
     */
    function closeRegister() {
        myManager.stop();
    }
    var myManager=new loopManager();
    /**
     * 循环方法管理器
     */
    function loopManager() {
        var that=this;
        this.flag=false;
        //启动获取登录注册的方法
        this.begin = function () {
            this.flag=false;
            this.loopHander();
        };
        this.stop = function () {
            this.flag=true;
            jeesnsDialog.closeAll();
        };
        /**
         * 具体循环方法
         */
        this.loopHander = function () {
            var s = that.getRegisterInfo();
            if(!that.flag){
                window.setTimeout(that.loopHander,5000);
            }

        };
        /**
         * 获取微服务确认登录信息
         */
        this.getRegisterInfo = function () {
            var s = 0;
            console.log('5秒只调用一次');
            //获取登录信息
            $.ajax({
             url: base + "/wechat/getWXXX/",
             type: "get",
             data: {
             },
             async: false,//同步获取
             cache: false,
             dataType: "json",
             timeout: 5000,
             error: function () {
             jeesnsDialog.errorTips("获取微信登录信息异常，请刷新重试")
             },
             success: function (res) {
                 if (res.code == 0) {
                     if(res.data.dlcode==200){
                         console.log("登录成功"+res)
                         that.flag = true;
                         closeRegister();
                         //刷新帐号列表
                         refMutAccount(getMutAccount);
                         s=1;
                     }else{

                     }
                 }
             }
             });
            return s;
        }
        
    }
   refMutAccount(getMutAccount);
    getNewsDatas();
    getNewMsgDetail();

    /**
     * 刷新多账号信息
     */
    function refMutAccount(callback) {
        //获取所有的登录信息
        $.ajax({
          url: base + "/wechat/getAllWXXX/",
          type: "get",
          data: { },
          cache: false,
          dataType: "json",
          timeout: 5000,
          error: function () {
          jeesnsDialog.errorTips("无法获取所有微信登录帐号！请联系管理员")
          },
          success: function (res) {
              if (res.code == 0) {
                  if(callback){
                      console.log(res.data);
                      callback(JSON.parse(res.data));
                  }
              }
          }
          });
    }

    /**
     * 获取多账号信息
     */
    function getMutAccount(res) {
        var str="";
        for(var index in res){
            var data=res[index];
            // data = JSON.parse(data);
            var nickName=data.user.NickName;
            if(nickName.indexOf('<span class="emoji')!=-1){
                nickName=nickName.substr(nickName.lastIndexOf("</span>")+7);
            }
            str+='<li username="'+data.user.UserName+'" Uin='+data.baseRequest.Uin+' NickName='+nickName+'><div class="avatar">' +
                '<img  class="img" src="'+data.user.HeadImgUrl+'" >' +
                '</div><div class="info"><h3 class="nickname"> ' +
                '<span  class="display_name ng-binding" >'+nickName+'</span>' +
                '<span class="total"></span></h3></div></li>';
        }
        $("#mutAccount .accountUl").html("");
        $("#mutAccount .accountUl").append(str);
        clearChooseButton();
    }
    /**
     * 账号切换
     */
    $('#mutAccount .accountUl').on('click','li',function(){　　　　
        var Uin=$(this).attr('Uin');
        var activeStr='active';
        $(this).parent().find('li').removeClass(activeStr);
        $(this).addClass(activeStr);
        dialogToUserName=$(this).attr('NickName');
        //获取所有联系人信息
        $.ajax({
            url: base + "/wechat/getContactByWXUIN/",
            data: {wxuin:Uin},
            cache: false,
            dataType: "json",
            timeout: 5000,
            error: function () {
                jeesnsDialog.errorTips("无法获取所有微信联系人信息！请联系管理员")
            },
            success: function (res) {
                if (res.code == 0) {
                    res = JSON.parse(res.data);
                   // dialogToUserName=res.wxuin;
                    $(".contactContent ul").html("");
                    $(".dialogContent ul").html("");
                    getDialog(res.groupChatList);
                    getContact(res.contactList);
                    groupChatList=res.groupChatList;
                    contactList=res.contactList;
                    $(".contactContent").hide();
                    $(".dialogContent").show();
                    $('#accountHander .handerNav .dialogLi').click();
                    $("#messageList").html('');
                }
            }
        });


    });
    /**  accountHander **/
    /**
     * 获取回话
     */
    function getDialog(res) {
        //合并数据，都是全局数据
        datas = res;
        var str="";

        for(var index in datas){
            var data=datas[index];
            var nickName=data.NickName;
            if(nickName.indexOf('<span class="emoji')!=-1){
                nickName=nickName.replace(/<span\s*[^>]*>(.*?)<\/span>/ig,"$1");
                if(nickName.trim()==''){
                    if(data.RemarkName!='') {
                        nickName=data.RemarkName;
                    }else {
                        nickName=data.Signature;
                    }
                }
            }
           /* var nickName=data.NickName;
            if(data.NickName.indexOf('<span class="emoji')!=-1){
                 nickName=nickName.substr(nickName.lastIndexOf("</span>")+7);
            }*/
            //群组，用nickname 来唯一标识
            str+='<li datatype="2" fromToUser=\"'+nickName+'-'+dialogToUserName+'\"  UserName='+data.UserName+' nickName='+nickName+' onclick="GroupDetail(this)"><div class="avatar">' +
                '<img class="img" src="'+data.HeadImgUrl+'" >' +
                '</div><div class="info">' +
                '<h3 class="nickname"> ' +
                '<span  class="display_name ng-binding" >'+nickName+'</span>' +
                // '<span class="time">'+data.time+'</span>'+
                '<span class="total"></span></h3>' +
                // '<div class="msgDiv"><span>'+data.lastMsg+'</span></div>' +
                '</div></li>';
        }
        $("#accountHander .dialogContent ul").html('');
        $("#accountHander .dialogContent ul").append(str);
    }

    /**
     * 获取通讯录
     */
    function getContact(res) {
        //合并数据，都是全局数据
        datas = res;
        var str="";
        for(var index in datas){
            var data=datas[index];
            var nickName=data.NickName;
            if(nickName.indexOf('<span class="emoji')!=-1){
                nickName=nickName.replace(/<span\s*[^>]*>(.*?)<\/span>/ig,"$1");
                if(nickName.trim()==''){
                    if(data.RemarkName!='') {
                        nickName=data.RemarkName;
                    }else {
                        nickName=data.Signature;
                    }
                }
            }
            var signature=data.Signature;
            if(signature.indexOf('<span class="emoji')!=-1){
                signature=signature.replace(/<span\s*[^>]*>(.*?)<\/span>/ig,"$1");
            }
            str+='<li  datatype="1" fromToUser='+nickName+'-'+dialogToUserName+' UserName='+data.UserName+' nickName='+nickName+' Signature="'+signature+'" Province="'+data.Province+'" onclick="GroupDetail(this)"><div class="avatar">' +
                '<img class="img" src="'+data.HeadImgUrl+'" >' +
                '</div><div class="info">' +
                '<h3 class="nickname"> ' +
                '<span  class="display_name ng-binding">'+nickName+'</span>' +
                '<span class="total"></h3>' +
                '</div></li>';
        }
        $("#accountHander .contactContent ul").html('');
        $("#accountHander .contactContent ul").append(str);
    }

    $('#accountHander .handerNav').on('click','li',function(){　　　　//动态事件绑定  为页面所有的dd添加一个事件 包括新增的节点
        var uuid=$(this).attr('uuid');
        var activeStr='active';
        $(this).parent().find('li span').removeClass(activeStr);
        $(this).find('span').addClass(activeStr);
        $(".dialogContent").hide();
        $(".contactContent").hide();
        if($(this).hasClass('dialogLi')){
            $(".dialogContent").show();
        }else if($(this).hasClass('contactsLi')){
            $(".contactContent").show();
        }
        $("#messageList").html('');
        clearChooseButton();
    });

    /**
     *  创建群成员
     */
    $('#addGroupPerson').on('click',function(){　　　　
        jeesnsDialog.open(base+'/res/modules/addGroupPerson.html','添加群成员','500px','500px',function (layero,index) {
            var body = layer.getChildFrame('body', index);
            //body.find(".name").hide();
            var checkboxGroup=body.find(".checkboxGroup");
            var contactArray=new Array();
            for(var index in contactList){
                var contact=contactList[index];
               contactArray.push(' <li><input type="checkbox" value="'+contact.UserName+'"><span>'+contact.NickName+'</span></li>');
            }
            checkboxGroup.append(contactArray.join(''));
            body.find(".save").bind('click',function () {
                var name=body.find(".name").val();
                var checkboxs= body.find("[type='checkbox']:checked");
                var tempArray=[];
               // tempArray.push($("#mutAccount .accountUl").find(".active").attr('username'));
                for(var i=0;i<checkboxs.length;i++){
                    tempArray.push(checkboxs[i].value);
                }
                addGroupPersonHander($("#mutAccount .accountUl").find(".active").attr('uin'),$("#accountHander li[fromToUser='" + dialogFromUserName+ "-" + dialogToUserName + "']").attr('username'),tempArray);
            })
            body.find(".cancel").bind('click',function () {
                jeesnsDialog.closeAll();
            });
        },function () {
            // closeRegister();
        });
    });
    /**
     * 创建群成员方法
     */
    function addGroupPersonHander(uin,chatRoomName,checkboxs) {
        var query={};
        query.wxuin=uin;
        query.chatRoomName=chatRoomName;
        query.addMemberList=checkboxs.toString();

        $.ajax({
            url: base + "/wechat/addToChatRoom",
            data: query,
            cache: false,
            dataType: "json",
          /*  timeout: 5000,*/
            error: function () {
                jeesnsDialog.errorTips("保存群成员失败")
            },
            success: function (res) {
                if (res.code == 0) {
                    res = JSON.parse(res.data);
                    jeesnsDialog.closeAll();
                    chooseAccount();
                }
            }
        });
    }


    /**
     *  添加群组
     */
    $('#groupPerson').on('click',function(){
        jeesnsDialog.open(base+'/res/modules/groupPerson.html','添加群组','500px','500px',function (layero,index) {
            var body = layer.getChildFrame('body', index);
            //body.find(".name").hide();
            var checkboxGroup=body.find(".checkboxGroup");
            var contactArray=new Array();
            for(var index in contactList){
                var contact=contactList[index];
                contactArray.push(' <li><input type="checkbox" value="'+contact.UserName+'"><span>'+contact.NickName+'</span></li>');
            }
            checkboxGroup.append(contactArray.join(""));
            body.find(".save").bind('click',function () {
                var name=body.find(".name").val();
                var checkboxs= body.find("[type='checkbox']:checked");
                var tempArray=[];
                tempArray.push($("#mutAccount .accountUl").find(".active").attr('username'));
                for(var i=0;i<checkboxs.length;i++){
                    tempArray.push(checkboxs[i].value);
                }
                addGroupHander($("#mutAccount .accountUl").find(".active").attr('uin'),name,tempArray);
            })
            body.find(".cancel").bind('click',function () {
                jeesnsDialog.closeAll();
            });
        },function () {
            // closeRegister();
        });
    });

    /**
     * 添加群方法
     */
    function addGroupHander(uin,name,checkboxs) {
        var query={};
        query.wxuin=uin;
        query.topic=name;
        query.memberList=checkboxs.toString();
        query.memberCount=checkboxs.length;

        $.ajax({
            url: base + "/wechat/createChatRoom/",
            data: query,
            cache: false,
            dataType: "json",
          /*  timeout: 5000,*/
            error: function () {
                jeesnsDialog.errorTips("添加群失败")
            },
            success: function (res) {
                if (res.code == 0) {
                    res = JSON.parse(res.data);
                    jeesnsDialog.closeAll();
                    chooseAccount();
                }
            }
        });
    }


    /**
     *  删除群成员
     */
    $('#delGroupPerson').on('click',function(){
        jeesnsDialog.open(base+'/res/modules/delGroupPerson.html','删除群成员','500px','500px',function (layero,index) {
            var body = layer.getChildFrame('body', index);
            //body.find(".name").hide();
           /* var checkboxGroup=body.find(".checkboxGroup");
            var contactArray=new Array();
            for(var index in contactList){
                var contact=contactList[index];
                contactArray.push(' <li><input type="checkbox" value="'+contact.UserName+'"><span>'+contact.NickName+'</span></li>');
            }
            checkboxGroup.append(contactArray.join());*/
            getGroupPersons(body);
            body.find(".save").bind('click',function () {
                var name=body.find(".name").val();
                var checkboxs= body.find("[type='checkbox']:checked");
                var tempArray=[];
                // tempArray.push($("#mutAccount .accountUl").find(".active").attr('username'));
                for(var i=0;i<checkboxs.length;i++){
                    tempArray.push(checkboxs[i].value);
                }
                delGroupHander($("#mutAccount .accountUl").find(".active").attr('uin'),$("#accountHander li[fromToUser='" + dialogFromUserName+ "-" + dialogToUserName + "']").attr('username'),tempArray);
            })
            body.find(".cancel").bind('click',function () {
                jeesnsDialog.closeAll();
            });
        },function () {
            // closeRegister();
        });
    });


    /**
     * 获取群成员
     */
    function getGroupPersons(body) {
        var query={};
        query.wxuin=$("#mutAccount .accountUl").find(".active").attr('uin');
        query.count=1;
        query.userName=$("#accountHander li[fromToUser='" + dialogFromUserName+ "-" + dialogToUserName + "']").attr('username');
        $.ajax({
            url: base + "/wechat/batchGetContact",
            data: query,
            cache: false,
            dataType: "json",
         /*   timeout: 5000,*/
            error: function () {
                jeesnsDialog.errorTips("获取群成员失败")
            },
            success: function (res) {
                if (res.code == 0) {
                    res = JSON.parse(res.data);
                    var checkboxGroup=body.find(".checkboxGroup");
                    var contactArray=[];
                    for(var index in res){
                        contactArray.push('<li><input type="checkbox" value="'+res[index].UserName+'"><span>'+res[index].NickName+'</span></li>');
                    }
                    checkboxGroup.append(contactArray.join(''));
                }

            }
        });
    }

    /**
     * 删除群成员
     */
    function delGroupHander(uin,chatRoomName,checkboxs) {
        var query={};
        query.wxuin=uin;
        query.chatRoomName=chatRoomName;
        query.username=checkboxs.toString();

        $.ajax({
            url: base + "/wechat/updateChatRoom",
            data: query,
            cache: false,
            dataType: "json",
          /*  timeout: 5000,*/
            error: function () {
                jeesnsDialog.errorTips("删除群成员失败")
            },
            success: function (res) {
                if (res.code == 0) {
                    res = JSON.parse(res.data);
                    jeesnsDialog.closeAll();
                    chooseAccount();
                }
            }
        });
    }


});

function chooseAccount(){
    $(".accountUl li.active").click();
}

function GroupDetail(obj) {
    clearChooseButton();
    var $this = $(obj);
    var $count = $("#mutAccount .accountUl").find(".active");
    $("#chatWin").show();
    $("#chatName").html($this.attr("nickName"));
    $("#toUsers").val($this.attr("UserName"));
    $("#wxuin").val($count.attr("uin"));
    dialogFromUserName=$this.attr("UserName");

    //$("#toUsers").val($this.attr("nickName"));
    dialogFromUserName=$this.attr("nickName");
    //$("#wxuin").val(dialogToUserName)

    $("#bgImg").attr('src',$this.find('.img').attr('src'));
    $('#deatilNickName').text($this.attr("nickName"));

    $("#messageList").html('');
    $this.find('.total').text('');
    pageNo=1;
    isLastPage=false;
    var datatype=$this.attr("datatype");
    $("#groupPerson").css('display','block');
    if(datatype=="1"){
        $("#Signature").text($this.attr("Signature"));
        $("#Province").text($this.attr("Province"));
        $(".Signature").css('display','block');
        $(".Province").css('display','block');

    }else if(datatype=='2'){
        $("#delGroupPerson").css('display','block');
        $("#addGroupPerson").css('display','block');
    }
    messageDate=null;


}

function clearChooseButton() {
    $("#groupPerson").css('display','none');
    $("#delGroupPerson").css('display','none');
    $("#addGroupPerson").css('display','none');
    $(".Signature").css('display','none');
    $(".Province").css('display','none');
    $("#bgImg").attr('src','');
    $("#deatilNickName").text('');
}


/*一直去获取未读信息*/
function getNewsDatas() {
    $.ajax({
        url: base + "/wechat/getAllNewMsg/",
        data: '',
        cache: false,
        dataType: "json",
        timeout: 5000,
        error: function (errorData) {
            //console.log();
            window.setTimeout(getNewsDatas,3000);
           // jeesnsDialog.errorTips("无法获取所有微信联系人信息！请联系管理员")
        },
        success: function (returnData) {
          /*  var tempdatas="[{'username':'1065619522','total':12,'rows':[" +
                "{'fromUserName':'@@f47cd0d6ca54e6f8748d2897d05f668d7fdbbc8f72fd84c084d4d6c379fb1909','toUserName':'1065619522','count':10},{'fromUserName':'@@e5a099e8c1456dc011a82dfafcb73301f61d70bb784e56c5c3de6cc4a7d6ebd1','toUserName':'1065619522','count':40}" +
                "]}]";*/
            var datas=returnData.data;
          /*  if(dialogFromUserName&&dialogFromUserName!='') {*/
                for (var index in datas) {
                    var data = datas[index];
                    if (data.username == dialogToUserName) {
                        handerDatas(data.rows);
                    }
                    setTodoMessage(data.username,data.total);
                }
         /*   }*/

            window.setTimeout(getNewsDatas,3000);
        }
    });
  /*  var reviceData=[{'MESSAGE':'dsfdsf',headImgUrl:'',username:'ddd','SENDDATE':'2017-1-22','SENDTIME':new Date().getTime()+''}];
    reviceAction(reviceData,dialogFromUserName,dialogToUserName);*/
}

/*一直去获取最新消息*/
function getNewMsgDetail() {
    if(dialogFromUserName&&dialogFromUserName!=''&&dialogToUserName&&dialogToUserName!='') {
        $.ajax({
            url: base + "/wechat/getNewMsgDetail",
            data: {
                formusername: encodeURIComponent(dialogFromUserName),
                tousername: encodeURIComponent(dialogToUserName)
            },
            cache: false,
            dataType: "json",
            timeout: 5000,
            error: function (errorData) {
                //console.log();
                window.setTimeout(getNewMsgDetail, 3000);
                // jeesnsDialog.errorTips("无法获取所有微信联系人信息！请联系管理员")
            },
            success: function (returnData) {
                /*  var tempdatas="[{'username':'1065619522','total':12,'rows':[" +
                 "{'fromUserName':'@@f47cd0d6ca54e6f8748d2897d05f668d7fdbbc8f72fd84c084d4d6c379fb1909','toUserName':'1065619522','count':10},{'fromUserName':'@@e5a099e8c1456dc011a82dfafcb73301f61d70bb784e56c5c3de6cc4a7d6ebd1','toUserName':'1065619522','count':40}" +
                 "]}]";*/
                var datas = returnData.data;
                for (var index in datas) {
                    var data = datas[index];
                    var content=data.content;
                    var desc='';
                    if(content.indexOf("@")!=-1){
                        content=content.substr(content.indexOf(":")+1);
                        desc='来自';
                    }
                    data.MESSAGE=content;
                    data.SENDDATE='2017-1-22';
                    data.SENDTIME=new Date().getTime()+'';
                  /*  data.username=data.formusername;*/
                    data.USERNAME=desc+data.formusername;
                    data.headImgUrl=data.headImgUrl;
                    if(!data.headImgUrl) {
                        var obj = $("#accountHander li[fromToUser='" + data.formusername + "-" + data.tousername + "']");
                        data.headImgUrl=obj.find("img").attr("src");
                    }
                    datas[index]=data;
                    //reviceAction(data, dialogFromUserName, dialogToUserName);
                }
                reviceAction(datas, dialogFromUserName, dialogToUserName);
                window.setTimeout(getNewMsgDetail, 3000);
            }
        });
    }else{
        window.setTimeout(getNewMsgDetail, 3000);
    }
    /*  var reviceData=[{'MESSAGE':'dsfdsf',headImgUrl:'',username:'ddd','SENDDATE':'2017-1-22','SENDTIME':new Date().getTime()+''}];
     reviceAction(reviceData,dialogFromUserName,dialogToUserName);*/
}
/**
* 根据最新数据和当前人比对，显示未读条数
* */
function handerDatas(datas) {
    if(datas&&datas.length>0){
        for(var index in datas){
            var data=datas[index];
            traverseMemberList(data);
        }
    }
}
/**
 * 在头像上显示未读信息
 */
function setTodoMessage(data,total) {
    //头像那边设置属性id，toUserName-fromUserName;
    //直接赋值就好
    if(data.formusername) {  //对操作栏设置未读信息
        var obj = $("#accountHander li[fromToUser='" + data.formusername + "-" + data.tousername + "']");
        if (obj && obj.length > 0) {
            obj.find(".total").text(data.count);
        }
    }else{  //对账号设置未读信息
        var obj=$(".accountUl li[nickname='"+data+"']");
        if (obj && obj.length > 0) {
            obj.find(".total").text(total);
        }
    }
}
/**
* 移动到头部，其他有带读数据，都移到上面，如果是当前对话框，移到最上面，
* */
function moveTop(flag,data) {
    /*if(flag){
        var obj = $("#accountHander .dialogContent li[fromToUser='" + data.formusername + "-" + data.tousername + "']");
        if (obj && obj.length > 0) {
            //obj.find(".total").text(data.count);
            obj.remove();
            $("#accountHander .dialogContent").prepend(obj);

        }
    }*/
}
/**
 * 遍历人员
 * @param data
 */
function traverseMemberList(data) {
    var tempgroupChatLists=groupChatList;
    for(var index in tempgroupChatLists){
        traverseHander(tempgroupChatLists[index],data);
    }
    var tempcontactLists=contactList;
    for(var index in contactList){
        traverseHander(contactList[index],data);
    }
}
/**
 * 遍历操作
 */
function traverseHander(persondata,data){
    //存在未读数据，
    if(data.formusername==persondata.NickName&&data.tousername==dialogToUserName){
        if(dialogFromUserName==data.formusername&&data.tousername==dialogToUserName){
            //在对话框内容中
            moveTop(true,data);
        }else{
            setTodoMessage(data);
            moveTop(false);
        }
    }
}



